/**
 * 
 */
package com.ws.framework.remoteservice.core.consumer;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.ws.framework.remoteservice.core.ex.WRSIException;


/**
 * @author WSH
 *
 */
public class JdkProxyFactory implements ProxyFactory {

	@Override
	public Object getProxy(ServiceAgent agent) {
		Class<?> contract;
		try {
			contract = Class.forName(agent.getContract());
		} catch (ClassNotFoundException e) {
			throw new WRSIException(e);
		}
		return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { contract },
				new JdkInvocationHandler(agent));
	}

	class JdkInvocationHandler implements InvocationHandler {

		private ServiceAgent agent;

		public JdkInvocationHandler(ServiceAgent agent) {
			this.agent = agent;
		}

		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			try {
				return agent.invoke(method, args);
			} catch (Exception ex) {
				throw ex;
			}
		}

	}
}
